package com.jianyun.jyzs.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;

import com.hannesdorfmann.mosby3.mvp.MvpActivity;
import com.jianyun.jyzs.MainActivity;
import com.jianyun.jyzs.R;
import com.jianyun.jyzs.bean.Account;
import com.jianyun.jyzs.bean.EnterInfo;
import com.jianyun.jyzs.dao.LoginDao;
import com.jianyun.jyzs.dao.MessageRemind;
import com.jianyun.jyzs.dao.ModelDao;
import com.jianyun.jyzs.presenter.LoginPresenter;
import com.jianyun.jyzs.utils.DeviceUtils;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.SystemUtils;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jianyun.jyzs.view.iview.ILoginView;
import com.jianyun.jyzs.widget.ClearWriteEditText;
import com.jianyun.jyzs.widget.LoadingDialog;
import com.jianyun.jyzs.widget.MoreWriteEditText;
import com.jrmf360.rylib.common.util.ToastUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by yangshijun on 2018/5/23.
 */

public class LoginActivity extends MvpActivity<ILoginView, LoginPresenter> implements ILoginView {


    @BindView(R.id.loginEnterprise)
    public MoreWriteEditText loginEnterprise;
    @BindView(R.id.loginAccount)
    public ClearWriteEditText loginAccount;
    @BindView(R.id.loginPwd)
    public ClearWriteEditText loginPwd;
    @BindView(R.id.loginToast)
    TextView loginToast;
    @BindView(R.id.loginButton)
    Button loginButton;


    private String account;//用户名
    private String pwd;   //密码
    private String enterprise;//企业号
    private LoadingDialog loadingDialog;
    private Account accountpwd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        UtilsStyle.setStatusBarMode(this,true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rce_activity_login);
        ButterKnife.bind(this);

        initData();
    }

    protected void initData() {
        initClearEditTextListener();
        loadingDialog = LoadingDialog.create(this).setDetailLabel(getString(R.string.rce_logging));
    }


    @OnClick(R.id.loginButton)
    public void onViewClicked() {
        account = loginAccount.getText().trim();
        pwd = loginPwd.getText().trim();
        enterprise = loginEnterprise.getText().toLowerCase().trim();
        //登录 TOP 1. 先获取建云中心URL
        getPresenter().getJyCenterURL(this,enterprise,account,pwd);

    }


    /**
     * 登录提示
     */
    private void hideLoginToast() {
        if (loginToast.getVisibility() == View.VISIBLE) {
            loginToast.setText(null);
        }
    }

    @NonNull
    @Override
    public LoginPresenter createPresenter() {
        return new LoginPresenter();
    }

    @Override
    public void LoginSuccess() {
        accountpwd = new Account(this.account, pwd);
        //数据库中插入
        EnterInfo enterInfo = new EnterInfo();
        enterInfo.setAccount(account);
        enterInfo.setPassword(pwd);
        enterInfo.setEnterinfo(enterprise);
        LoginDao loginDao = new LoginDao(LoginActivity.this);
        boolean isEnterInfo = loginDao.getEnterInfo(enterInfo);
        if (isEnterInfo){
            enterInfo.setAutoId(loginDao.getEnterInfoID(enterInfo));
            loginDao.update(enterInfo);
        }else {
            loginDao.insert(enterInfo);
        }
        LoginCache.getInstance().setLoginTure(true);
        if (accountpwd!=null)LoginCache.getInstance().setLoginInfo(accountpwd);
        MessageRemind remind = new MessageRemind(this);
        ModelDao modelDao = new ModelDao(this);
        Intent intent = new Intent(this, MainActivity.class);
        loadingDialog.dismiss();
        startActivity(intent);
        finish();
    }

    @Override
    public void LoginFaile() {
        loginToast.setVisibility(View.VISIBLE);
        loginToast.setText("登录失败！");
        LoginCache.getInstance().setLoginTure(false);
    }

    @Override
    public void showLoginExpetion(String msg) {
        loginToast.setVisibility(View.VISIBLE);
        loginToast.setText(msg);
        LoginCache.getInstance().setLoginTure(false);
        //loadingDialog.dismiss();
    }

    @Override
    protected void onResume() {
        super.onResume();

    }





    @Override
    public void showLoading() {
        loadingDialog.show();
    }

    @Override
    public void hintLoading() {
        loadingDialog.dismiss();
    }

    @Override
    public void getCenterUrl(boolean isSuccess, String msg) {
        if (isSuccess){
            //获取url成功
            String phoneType=android.os.Build.MODEL;
            String osVersion=android.os.Build.VERSION.RELEASE;
            //开始登录
            getPresenter().startLogin(enterprise,account,pwd,"1.0.2");
        }else {
            loadingDialog.dismiss();
            ToastUtil.showNoWaitToast(this,msg);
        }
    }

    /**
     * 输入框监听 以及清除账号 密码 企业号 缓存
     */
    private void initClearEditTextListener() {
        loginEnterprise.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() >= 1) {
                    String password = loginPwd.getText();
                    String loginAccountText = loginAccount.getText();
                    if (!TextUtils.isEmpty(password)&&!TextUtils.isEmpty(loginAccountText)) {
                        loginButton.setEnabled(true);
                        return;
                    }
                }
                loginButton.setEnabled(false);
                hideLoginToast();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        loginAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() >= 1) {
                    String password = loginPwd.getText();
                    if (!TextUtils.isEmpty(password)) {
                        loginButton.setEnabled(true);
                        return;
                    }
                }
                loginButton.setEnabled(false);
                hideLoginToast();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        loginAccount.addTextClearListener(new ClearWriteEditText.OnTextClearListener() {
            @Override
            public void onTextClear(View v) {
                loginPwd.setText("");
            }
        });
        loginPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                hideLoginToast();
                if (s.length() >= 1) {
                    String account = loginAccount.getText();
                    if (!TextUtils.isEmpty(account)) {
                        loginButton.setEnabled(true);
                        return;
                    }
                }
                loginButton.setEnabled(false);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /**
     *
     * 触摸事件优化
     * @param event
     * @return
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (null != this.getCurrentFocus() && event.getAction() == MotionEvent.ACTION_UP) {
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
//            login(LoginStatus.LOGIN_STATUS.online);
            return true;
        }
        return super.dispatchKeyEvent(event);
    }
}
